package com.project.demo.service.edu;

import cn.hutool.core.io.FileTypeUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project.demo.base.BeanConvert;
import com.project.demo.dao.EduChapterMapper;
import com.project.demo.dao.EduCourseMapper;
import com.project.demo.dao.EduVideoMapper;
import com.project.demo.entity.EduCourseEntity;
import com.project.demo.entity.edu.EduChapterEntity;
import com.project.demo.entity.edu.EduVideoEntity;
import com.project.demo.entity.param.EduCourseSearchParam;
import com.project.demo.entity.vo.EduCourseDetailVO;
import com.project.demo.entity.vo.EduCourseSimpleVO;
import com.project.demo.entity.vo.PageResult;
import com.project.demo.entity.vo.R;
import com.project.demo.entity.vo.teacher.EduChapterVO;
import com.project.demo.entity.vo.teacher.EduVideoVO;
import com.project.demo.enums.CourseStatusEnum;
import com.project.demo.service.AliyunOssService;
import com.project.demo.service.AliyunVodService;
import com.project.demo.service.base.BaseService;
import com.project.demo.util.LambdaTypeUtils;
import com.project.demo.util.RUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;


@Service
public class EduOnlineService extends BaseService<EduCourseEntity> {

	@Resource
	private EduCourseMapper eduCourseMapper;

	@Autowired
	private AliyunOssService aliyunOssService;

	@Resource
	private EduChapterMapper eduChapterMapper;

	@Resource
	private EduVideoMapper eduVideoMapper;

	@Resource
	private AliyunVodService aliyunVodService;

	public R getDraft(Integer userId) {
		List<EduCourseEntity> entityList = eduCourseMapper.selectList(
				Wrappers.lambdaQuery(EduCourseEntity.class)
						.eq(EduCourseEntity::getTeacherId, userId)
						.eq(EduCourseEntity::getStatus, CourseStatusEnum.DRAFT)
		);
		if (CollectionUtils.isEmpty(entityList)) {
			return RUtils.success("该讲师没有在草稿箱的课程");
		}
		EduCourseEntity entity = entityList.get(0);
		BeanConvert result = new EduCourseDetailVO().convertFrom(entity);
		return RUtils.success("该讲师在草稿箱的课程", result);
	}

	public R createCourse(EduCourseDetailVO vo, MultipartFile file) throws IOException {
		if (Objects.nonNull(file)) {
			R r = updateAvatar(null, file);
			vo.setCover((String) r.getData());
		}
		// 转换数据
		EduCourseEntity entity = vo.convertTo(new EduCourseEntity());
		entity.setBuyCount(0)
				.setViewCount(0);
		// 执行插入
		eduCourseMapper.insert(entity);
		return RUtils.success("创建课程成功", entity);
	}


	/**
	 * 返回图片url（针对管理员更新）
	 * 如果userId不为空且大于0，则删除目标用户头像,
	 */
	public R updateAvatar(Integer userId, MultipartFile file) throws IOException {
		// 图片大小限制在 2MB
		if (file.getSize() > 2097152L) {
			return RUtils.fail("图片文件不能超过2MB");
		}
		String type = FileTypeUtil.getType(file.getInputStream());
		// 判断是否目标格式图片文件
		if ("jpg".equals(type) || "jpeg".equals(type) || "png".equals(type)) {
			String newAvatarUrl = aliyunOssService.upload(file);
			// 头像上传成功
			if (StringUtils.hasText(newAvatarUrl)) {
				if (Objects.nonNull(userId) && userId > 0) {
					EduCourseEntity entity = eduCourseMapper.selectById(userId);
					if (Objects.isNull(entity)) {
						return RUtils.fail("课程不存在");
					}
					// 删除原有图片
					aliyunOssService.delete(entity.getCover());
				}
				return RUtils.success("新图片URL", newAvatarUrl);
			}
		} else {
			return RUtils.fail("图片格式不支持");
		}
		return RUtils.fail("课程更新出错");
	}

	public List<EduChapterVO> listChapters(Integer courseId) {
		List<EduChapterEntity> entityList = eduChapterMapper.selectList(
				Wrappers.lambdaQuery(EduChapterEntity.class)
						.eq(EduChapterEntity::getCourseId, courseId)
						.orderByAsc(EduChapterEntity::getSort)
						.orderByAsc(EduChapterEntity::getTitle)
		);
		if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isEmpty(entityList)) {
			return Collections.emptyList();
		}
		return covertToVO(entityList);
	}

	public List<EduChapterVO> covertToVO(List<EduChapterEntity> entityList) {
		return entityList.stream()
				.parallel()
				.map(e -> (EduChapterVO) new EduChapterVO().convertFrom(e))
				.collect(Collectors.toList());
	}


	/**
	 * 新建章节
	 */
	public R create(EduChapterVO vo) {
		EduChapterEntity entity = vo.convertTo(new EduChapterEntity());
		eduChapterMapper.insert(entity);
		return RUtils.success("章节创建成功", entity);
	}

	/**
	 * 更新章节信息
	 */
	public R update(EduChapterVO vo) {
		String title = vo.getTitle();
		Integer sort = vo.getSort();
		int i = eduChapterMapper.update(null,
				Wrappers.lambdaUpdate(EduChapterEntity.class)
						.eq(EduChapterEntity::getId, vo.getId())
						.set(StringUtils.hasText(title), EduChapterEntity::getTitle, title)
						.set(Objects.nonNull(sort), EduChapterEntity::getSort, sort)
		);
		return RUtils.commonFailOrNot(i, "章节信息更新");
	}

	/**
	 * 删除章节（如果章节下有视频，将全部删除）
	 */
	public R delete(int chapterId) {
		int i = eduChapterMapper.deleteById(chapterId);
		if (i > 0) {
			// 删除视频与文件
			List<EduVideoEntity> videoEntityList = eduVideoMapper.selectList(
					Wrappers.lambdaQuery(EduVideoEntity.class)
							.select(EduVideoEntity::getId, EduVideoEntity::getVideoId)
							.eq(EduVideoEntity::getChapterId, chapterId)
			);
			ArrayList<Integer> videoId = new ArrayList<>();
			ArrayList<String> videoSourceId = new ArrayList<>();
			videoEntityList.forEach(e -> {
				videoId.add(e.getId());
				videoSourceId.add(e.getVideoId());
			});
			if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(videoId)) {
				eduVideoMapper.deleteBatchIds(videoId);
			}
			if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isEmpty(videoSourceId)) {
				aliyunVodService.deleteVideos(videoSourceId);
			}
		}
		return RUtils.commonFailOrNot(i, "章节删除");
	}


	public boolean changeStatus(int Id, CourseStatusEnum status) {
		int i = eduCourseMapper.update(null,
				Wrappers.lambdaUpdate(EduCourseEntity.class)
						.eq(EduCourseEntity::getId, Id)
						.set(EduCourseEntity::getStatus, status)
		);
		return i > 0;
	}

	public R courseList(EduCourseSearchParam param) {
		String title = param.getTitle();
		Integer teacherId = param.getTeacherId();
		Integer subjectId = param.getSubjectId();
		Boolean free = param.getFree();
		CourseStatusEnum status = param.getStatus();
		Boolean enable = param.getEnable();
		// 条件构造
		Page<EduCourseEntity> page = new Page<>(param.getCurrent(), param.getPageSize());

		Wrapper<EduCourseEntity> wrapper = Wrappers.lambdaQuery(EduCourseEntity.class)
				.select(tfi -> !tfi.getColumn().equals(LambdaTypeUtils.getColumnName(EduCourseEntity::getDescription)))
				.eq(Objects.nonNull(enable), EduCourseEntity::getEnable, enable)
				.eq(Objects.nonNull(teacherId), EduCourseEntity::getTeacherId, teacherId)
				.eq(Objects.nonNull(subjectId), EduCourseEntity::getSubjectId, subjectId)
				// 免费
				.eq(Objects.nonNull(free) && free, EduCourseEntity::getPrice, 0)
				// 收费
				.gt(Objects.nonNull(free) && !free, EduCourseEntity::getPrice, 0)
				// 非 CourseStatusEnum.AUDITING
				.eq(Objects.nonNull(status) && !CourseStatusEnum.AUDITING.equals(status),
						EduCourseEntity::getStatus, status)
				.and(CourseStatusEnum.AUDITING.equals(status),
						wrp -> wrp.eq(EduCourseEntity::getStatus, CourseStatusEnum.FIRST_AUDITING)
								.or()
								.eq(EduCourseEntity::getStatus, CourseStatusEnum.SECOND_AUDITING)
				)
				.like(StringUtils.hasText(title), EduCourseEntity::getTitle, title)
				.orderByAsc(EduCourseEntity::getSort);
		// 分页查询
		Page<EduCourseEntity> entityPage = eduCourseMapper.selectPage(page, wrapper);
		// 数据转换
		PageResult<EduCourseSimpleVO> voPageResult = covertToPageResult(entityPage, true);
		// 返回
		return RUtils.success("课程列表信息", voPageResult);
	}

	public PageResult<EduCourseSimpleVO> covertToPageResult(IPage<EduCourseEntity> entityIPage,
	                                                        boolean getSubjectParent) {
		List<EduCourseSimpleVO> voList = entityIPage.getRecords().stream()
				.parallel()
				.map(e -> {
					EduCourseSimpleVO vo = new EduCourseSimpleVO().convertFrom(e);
					// 获取分类等级
                   /* if (getSubjectParent && Objects.nonNull(vo.getSubjectId())) {
                        vo.setSubjectParent(eduSubjectService.listAllParent(vo.getSubjectId()));
                    }*/
					// 获取教师名字
                   /* if (Objects.nonNull(vo.getTeacherId())) {
                        EduTeacherEntity entity = eduTeacherMapper.selectOne(
                                Wrappers.lambdaQuery(EduTeacherEntity.class)
                                        .select(EduTeacherEntity::getName)
                                        .eq(EduTeacherEntity::getId, vo.getTeacherId())
                        );
                        vo.setTeacherName(entity.getName());
                    }*/
					return vo;
				})
				.collect(Collectors.toList());
		return new PageResult<>(entityIPage.getTotal(), voList);
	}

	public R listForApp(EduCourseSearchParam param) {
		String title = param.getTitle();
		Integer teacherId = param.getTeacherId();
		Integer subjectId = param.getSubjectId();
		// 条件构造
		Page<EduCourseEntity> page = new Page<>(param.getCurrent(), param.getPageSize());
		Wrapper<EduCourseEntity> wrapper = Wrappers.lambdaQuery(EduCourseEntity.class)
				.select(tfi -> !tfi.getColumn().equals(LambdaTypeUtils.getColumnName(EduCourseEntity::getDescription)))
				.like(StringUtils.hasText(title), EduCourseEntity::getTitle, title)
				.orderByAsc(EduCourseEntity::getSort);
		// 分页查询
		Page<EduCourseEntity> entityPage = eduCourseMapper.selectPage(page, wrapper);
		// 数据转换
		PageResult<EduCourseSimpleVO> voPageResult = covertToPageResult(entityPage, false);
		// 返回
		return RUtils.success("课程列表信息", voPageResult);
	}

	public R getDetails(Integer id) {
		EduCourseEntity entity = eduCourseMapper.selectById(id);
		EduCourseDetailVO result = new EduCourseDetailVO().convertFrom(entity);
		return RUtils.success("课程详细", result);
	}

	public List<EduVideoVO> listVideos(Integer chapterId) {
		List<EduVideoEntity> entityList = eduVideoMapper.selectList(
				Wrappers.lambdaQuery(EduVideoEntity.class)
						.eq(EduVideoEntity::getChapterId, chapterId)
						.orderByAsc(EduVideoEntity::getSort)
						.orderByAsc(EduVideoEntity::getTitle)
		);
		if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isEmpty(entityList)) {
			return Collections.emptyList();
		}
		return covertToVO1(entityList);
	}

	public List<EduVideoVO> covertToVO1(List<EduVideoEntity> entityList) {
		return entityList.stream()
				.parallel()
				.map(e -> (EduVideoVO) new EduVideoVO().convertFrom(e))
				.collect(Collectors.toList());
	}
}
